<!--
 * @description  : 案件-鉴别检验物品审批表文书
 * @descriptionDetail: 案件-鉴别检验物品审批表文书
 * @copyright    : 浙江烟草
 * @author       : sy
 * @create       : 2022-07-27 15:43:11
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :isWhite="true" backText="返回" :title="navTitle">
      <view class="theme-color" @click="printOrDown(state.canEdit)">
        {{ state.canEdit?'预览':'打印' }}
      </view>
    </theme-navbar>
    <!-- #endif -->
		<!-- #ifdef H5-WECHAT || H5-EMP -->
		<fab-button :content="state.canEdit?fContent:fContents" @fabtrigger="fabtrigger" />
		<!-- #endif -->
    <view class="top-title-content">
      <view class="main-title">
        {{ goodsApproForm.orgShortname }}
      </view>
      <view class="sub-title">
        鉴别检验物品审批表
      </view>
      <view class="content-detail">
        <u-input placeholder="请输入" :disabled="true" input-align="center" v-model="goodsApproForm.fullDocNo" />
      </view>
    </view>
    <u-gap height="20" bg-color="#f2f2f2"></u-gap>
    <view class="main-content">
      <u-form :model="goodsApproForm" :error-type="errorType" :rules="rules" class="form-content" ref="uForm">
        <u-form-item label="当事人" :label-width="labelWidth" :required="isRequired">
          <u-input placeholder="请填写当事人" input-align="right" :disabled="true" v-model="goodsApproForm.party" />
        </u-form-item>
        <u-form-item label="先行登记保存通知书编号" :label-position="labelPosition" :right-icon="state.canEdit&&goodsApproForm.regSize!='1'?'arrow-right':''">
          <u-input placeholder="请填写先行登记保存通知书编号" :disabled="true" v-model="goodsApproForm.regNo" @click="()=>{if(state.canEdit&&goodsApproForm.regSize!='1') layoutShow = true}" />
        </u-form-item>
        <u-form-item label="鉴别检验事由" :label-position="labelPosition" :required="isRequired" prop="samplingReason">
          <u-input placeholder="请填写鉴别检验事由" :disabled="true" v-model="goodsApproForm.samplingReason" />
        </u-form-item>
        <u-form-item :label-position="labelPosition" label="备注">
          <u-input type="textarea" :maxlength="maxLength" :disabled="!state.canEdit" v-model="goodsApproForm.remark" />
        </u-form-item>
        <u-form-item :border-bottom="false">
          <!-- 鉴别检验物品 选择 -->
          <view class="" style="width: 100%;" @click="goodsListShow = !goodsListShow">
            <u-cell-group :border="false">
              <u-cell-item title="鉴别检验物品" :title-style="titSty" :border="false" hover-class="none" :arrow-direction="arrow"></u-cell-item>
            </u-cell-group>
            <view class="" v-show="goodsListShow">
              <u-table font-size="26">
                <u-tr class="u-tr">
                  <u-th class="u-th" width="33%">
                    品名
                  </u-th>
                  <u-th class="u-th">
                    规格
                  </u-th>
                  <u-th class="u-th">
                    样品基数(条)
                  </u-th>
                  <u-th class="u-th">
                    样品数量(条)
                  </u-th>
                </u-tr>
                <u-tr class="u-tr" v-for="(item) in goodsApproForm.goods" :key="item.goodsUuid">
                  <u-td class="u-td" width="33%">
                    <u-input :disabled="true" placeholder="" input-align="center" v-model="item.goodsName" />
                  </u-td>
                  <u-td class="u-td">
                    <u-input :disabled="true" placeholder="" input-align="center" v-model="item.spec" />
                  </u-td>
                  <u-td class="u-td">
                    <u-input :disabled="true" placeholder="" input-align="center" v-model="item.baseQty" />
                  </u-td>
                  <u-td class="u-td">
                    <u-input :disabled="!state.canEdit" placeholder="" input-align="center" v-model="item.sampleQty" @blur="handleSampleQty(item)" />
                  </u-td>
                </u-tr>
              </u-table>
            </view>
          </view>
        </u-form-item>
      </u-form>
    </view>
    <!-- 承办人意见 -->
    <view class="audit-box">
      <u-gap height="20" bg-color="#f2f2f2"></u-gap>
      <view class="audit-content">
        <view class="audit-title" style="display: inline-flex;flex-direction: row;width: 100%;justify-content: space-between;align-items: center;">
          <text>承办人意见</text>
          <u-icon
            customPrefix="csbi-icon"
            name="moban"
            size="40"
            :color="$theme.u_type_primary"
            @click="tapFieldPress('undertakerAdvice')"
          ></u-icon>
        </view>
        <view class="audit-text">
          <u-input type="textarea" placeholder="请输入" :disabled="!state.canEdit" v-model="goodsApproForm.undertakerAdvice" />
        </view>
        <view class="audit-person">
          <u-input placeholder="请选择" input-align="right" :disabled="true" :clearable="false" v-model="goodsApproForm.undertaker" @click="()=>{if(state.canEdit) personSelectShow = true}" />
        </view>
        <view class="audit-date">
          <u-input placeholder="请选择" input-align="right" :disabled="true" :clearable="false" v-model="goodsApproForm.undertakerTime" @click="()=>{if(state.canEdit) isShowRegDate = true}" />
        </view>
      </view>
    </view>
    <view class="audit-box" v-if="!state.canEdit">
      <view v-for="(ao,index) in approves" :key="index">
        <u-gap height="20" bg-color="#f2f2f2"></u-gap>
        <view class="audit-content">
          <view class="audit-title">
            <text class="audit-require">
              *
            </text>{{ ao.flowNode.displayName }}
          </view>
          <view class="audit-text">
            <u-input type="textarea" placeholder="" :disabled="true" v-model="goodsApproForm['_approveInfo'+ao.gfaCode]" />
          </view>
          <view class="audit-person">
            <u-input placeholder="签名" input-align="right" :disabled="true" :clearable="false" v-model="goodsApproForm['_approvePersonName'+ao.gfaCode]" />
          </view>
          <view class="audit-date">
            <u-input placeholder="年  月  日" input-align="right" :disabled="true" :clearable="false" v-model="goodsApproForm['_approveDate'+ao.gfaCode]" />
          </view>
        </view>
      </view>
    </view>

    <!-- 底部按钮开始 -->
    <view class="bottom-btn-info" v-if="state.canEdit">
      <u-row gutter="16">
        <u-col span="6">
          <u-button plain type="primary" @click="submitBtn('save')">
            保存
          </u-button>
        </u-col>
        <u-col span="6">
          <u-button type="primary" @click="submitBtn('submit')">
            提交
          </u-button>
        </u-col>
      </u-row>
    </view>
    <!-- 底部按钮结束 -->

    <!-- 物品选择 -->
    <u-popup mode="bottom" border-radius="14" height="80%" v-model="layoutShow">
      <goods-sele-com :caseUuid="caseParam.caseUuid" @m-select="handlerSelectlayout"></goods-sele-com>
    </u-popup>
    <!-- 人员选择 -->
    <u-popup mode="bottom" height="80%" v-model="personSelectShow">
      <person-selection :params="psParam" @choose="handlerChoosePerson"></person-selection>
    </u-popup>
    <u-calendar :mode="mode" :max-date="maxDate" v-model="isShowRegDate" @change="changeDate('undertakerTime',$event)">
    </u-calendar>
    <u-popup mode="bottom" height="80%" v-model="showFieldTpl">
      <doc-form-content-tep :params="fieldParam" formName="goodsApproForm" :fieldkey="fieldKey" @choice="choiceFieldTpl"></doc-form-content-tep>
    </u-popup>
    <u-popup mode="bottom" height="80%" v-model="showFieldTpl">
      <doc-form-content-tep
        :params="fieldParam"
        formName="goodsApproForm"
        :fieldkey="fieldKey"
        @choice="choiceFieldTpl"
      ></doc-form-content-tep>
    </u-popup>
  </view>
</template>

<script>
	import caseCommon from "../caseCommonMixin.js";
	import caseService from "@/service/case/case.service";
	import officeService from "@/service/case/office.service.js";
	import PersonSelection from "@/pages/case/components/personSelection.vue";
	import GoodsSeleCom from "@/pages/case/components/goodsSeleCom.vue";
	import {
		dateUtils,
	} from "@/common/util";
	import DocFormContentTep from "../components/docFormContentTemplate.vue";
	import fabButton from '@/components/uni-fab.vue';

	export default {
		components: {
			PersonSelection,
			GoodsSeleCom,
			DocFormContentTep,
			fabButton
		},
		mixins: [caseCommon, ],
		data() {
			return {
				mode: 'date',
				maxDate: '2099-12-31',
				isShowRegDate: false,
				errorType: ['border-bottom', 'message', ],
				isRequired: true,
				labelWidth: '220',
				labelPosition: 'top',
				maxLength: 9999,
				employeeLst: [], // 选择人员数据
				caseParam: {}, // 上个页面传过来的参数
				goodsApproForm: {},
				doc: {},
				layoutShow: false,
				personSelectShow: false,
				isApprovePerson: false, // 是否是审核人
				psParam: {
					min: 2,
					max: 2,
				},
				approves: [],
				rules: {
					// samplingReason:[{
					//   required:true,
					//   message: '请填写鉴别检验事由',
					//   trigger: ['change', 'blur',],
					// },],
				},
				goodsListShow: true,
				titSty: {
					'font-size': '32rpx',
					'padding-left': '0rpx',
				},
				goodsList: [],
				fContent: [{
					iconPath: require('@/static/oview.png'),
					selectedIconPath: require('@/static/oview.png'),
					text: '预览',
					active: false,
				}],
				fContents: [{
					iconPath: require('@/static/dy.png'),
					selectedIconPath: require('@/static/dy.png'),
					text: '打印',
					active: false,
				}]
			}
		},
		computed: {
			arrow() {
				return this.goodsListShow ? "down" : "right";
			},
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		onLoad() {
			this.caseParam = this.getRouteParam();
			this.psParam.caseUuid = this.caseParam.caseUuid;
		},
		mounted() {
			this.docStep((docInfo) => {
				this.doc = docInfo ? docInfo : {};
				this.setRightBtns();
			});
			this.initDocData();

		},
		methods: {
			// 设置右侧标题
			setRightBtns() {
				// #ifdef H5-DINGDING
				this.$deviceApi.setRight(this.state.canEdit ? '预览' : '打印', () => {
					this.printOrDown(this.state.canEdit);
					this.setRightBtns();
				}, true, true);
				// #endif
			},
			fabtrigger(btn) {
				if (btn.index == 0) {
					this.printOrDown(this.state.canEdit);
				}
			},
			initDocData() {
				officeService.docFields(this.caseParam.docUuid, true).then(docConfigs => {
					if (docConfigs.success) {
						this.docFields = [...docConfigs.data, ];
						this.$modal.showLoading("文书加载中...");
						let self = this;
						// 承办人意见，流程信息
						Promise.all([
							officeService.getDocGoodsApproval({
								id: this.caseParam.id,
								docUuid: this.caseParam.docUuid,
								bizUuid: this.caseParam.bizUuid,
							}),
							officeService.approves({
								id: this.caseParam.id,
								docUuid: this.caseParam.docUuid,
							}),
						]).then(_docs => {
							let [tiInfo, rs, ] = [{}, {}, ];
							if (_docs[0].data.length === 2) {
								tiInfo = _docs[0].data[0];
								rs = _docs[0].data[1];
								Object.keys(tiInfo).forEach(key => {
									rs[key] = tiInfo[key];
								});
								rs['regNo'] = tiInfo.regNo || '';
								rs['goods'] = tiInfo.goods || '';
								rs['regSize'] = tiInfo.regSize || '';
							} else {
								rs = _docs[0].data[0];
							}
							this.goodsApproForm = rs;
							this.approves = _docs[1].data;
							this.approves.forEach((item) => {
								this.goodsApproForm['_approveInfo' + item.gfaCode] = item.approveInfo || '';
								this.goodsApproForm['_approvePersonUuid' + item.gfaCode] = item.approvePersonUuid || '';
								this.goodsApproForm['_approvePersonName' + item.gfaCode] = item.approvePersonName || '';
								this.goodsApproForm['_approveDate' + item.gfaCode] = item.approveDate ? item.approveDate : (item.step == item.flowNode.nodeCode ? dateUtils.dateFormat('yyyy年MM月dd日', new Date()) : '');
							});
							self.$modal.hideLoading();
						}, (err) => {
							self.$modal.hideLoading();
							self.$u.toast(err);
						});
					}
				});

			},
			// 打印/预览
			printOrDown(flag) {
				if (flag) {
					// 调接口预览
					this.submitBtn('preview');
				} else {
					this.downloadFile(this.doc.pdfFileId);
				}
			},
			downloadFile(fileId, titleName, isDownload) {
				let pdfIds = fileId;
				if (!pdfIds) {
					this.$u.toast("没有文书");
					return;
				}
				this.setRouteParam({
					fileId: pdfIds,
					fileName: titleName,
					isDownload: isDownload,
				});
				this.$u.route('pages/commonPage/printerComponent');
			},
			changeDate(type, e) {
				this.goodsApproForm[type] = dateUtils.dateFormat("yyyy年MM月dd日", new Date(e.result));
			},
			// 选择执行人
			handlerChoosePerson(e) {
				this.personSelectShow = false;
				// 提交选择审核人
				if (this.isApprovePerson) {
					let nextP = [];
					e.forEach((item) => {
						nextP.push(item.personId);
					});
					this.submitDocInfo('submit', nextP.join(','));
				} else {
					this.employeeLst = [...e, ];
					let tIds = [];
					let tNames = [];
					this.employeeLst.forEach(el => {
						tIds.push(el.personUuid);
						tNames.push(el.personName + "(" + el.leCertNo + ")");
					});
					this.goodsApproForm['undertakerUuids'] = tIds.join(",");
					this.goodsApproForm['undertaker'] = tNames.join(",");
				}
			},
			// 表单验证
			validForm() {
				let basicValid = false;
				this.$refs.uForm.validate(valid => {
					if (valid) {
						basicValid = true;
					} else {
						basicValid = false;
					}
				});
				return basicValid;
			},
			submitBtn(type) {
				// 点击提交、保存按钮
				let flag = this.validForm();
				if (flag) {
					if (this.goodsApproForm.goods && this.goodsApproForm.goods.length > 0) {
						if (type == 'submit') {
							// 选择审核人
							this.choseAuditPsr('docSampleGoodsApproval');
						} else if (type == 'save') {
							this.submitDocInfo(type);
						} else { // 预览
							if (!this.doc.isRecorded) {
								this.$u.toast('请先保存数据');
								return;
							}
							officeService.buildLocalPunish("/build/doc-sample-goods-approval", this.doc.docInsUuid).then(pdfId => {
								if (pdfId.success) {
									this.downloadFile(pdfId.bean, "预览", false);
								} else {
									this.$u.toast(pdfId.msg);
								}
							});
						}
					} else {
						this.$modal.alert("无抽样物品，或抽样数量为空。请添加抽样物品及抽样数量");
					}
				}
			},
			// 物品校验
			handleSampleQty(goods) {
				if (goods.baseQty) {
					if (Number(goods.sampleQty) > Number(goods.baseQty)) {
						this.$u.toast(`${goods.goodsName}的样品数量不能大于样品基数，请重新输入！'`);
						this.$set(goods, 'sampleQty', '');
					}
				}
			},
			// 保存/提交接口
			submitDocInfo(type, nextPersons) {
				let [docGoodsReg, self, ] = [this.goodsApproForm, this, ];
				let {
					id,
					docUuid,
					titemUuid,
				} = this.caseParam;
				docGoodsReg.caseUuid = this.caseParam.bizUuid;
				type === 'save' && (this.$u.loading('数据保存中...'));
				officeService.saveDocGoodsApproval(docGoodsReg, docUuid, titemUuid, id, this.caseParam.type).then(res => {
					this.$u.hideLoading();
					if (res.success) {
						this.$u.toast(res.msg);
						this.goodsApproForm = res.bean;
						self.doc['isRecorded'] = res.data[0].isRecorded;
						self.doc['docInsUuid'] = res.data[0].docInsUuid;
						if (type == 'submit') {
							this.$u.loading('数据提交中...');
							officeService.submitDocGoodsApproval(docGoodsReg, docUuid, titemUuid, res.data[0].docInsUuid, this.caseParam.type, nextPersons).then(res => {
								this.$u.hideLoading();
								this.$u.toast(res.msg);
								this.saveBehaviorLog(1, this.caseParam, this.doc);
								if (res.success) {
									self.backPrev({
										paramKey: "offiList",
										param: {
											caseUuid: this.caseParam.bizUuid,
											caseCode: this.caseParam.caseCode,
											caseType: this.caseParam.caseType,
										},
									});
								}
							});
						} else {
							this.saveBehaviorLog(0, this.caseParam, this.doc);
						}
					} else {
						this.$u.toast(res.msg);
					}

				});
			},
			// 提交时选择审核人
			choseAuditPsr(gfaCode) {
				this.isApprovePerson = true;
				this.psParam = {
					min: 1,
					selectedPsrLst: [],
					dataHandler: (psrName) => {
						return caseService.getNextFlowUsers({
							page: 1,
							limit: 20,
							personName: psrName,
							gfCode: gfaCode,
						}).then(res => {
							if (res.success) {
								return res.data;
							} else {
								return [];
							}
						});
					},
				};
				this.personSelectShow = true;
			},
			// 选择物品返回
			handlerSelectlayout(pItems) {
				this.layoutShow = false;
				this.goodsApproForm.goods = [];
				this.$set(this.goodsApproForm, 'goods', [...pItems, ]);
			},
		},
	}
</script>
<style lang="scss" scoped>
	@import "../case_common.scss";

	/deep/ .main-content .u-cell {
		padding-left: 0px;
	}

	.u-td {
		white-space: nowrap;
		overflow: hidden;
	}
</style>
